package com.serialPort.web.service.impl;

import cn.hutool.json.JSONObject;
import com.serialPort.common.utils.HttpClientUtils;
import com.serialPort.web.domain.HL7Message;
import com.serialPort.web.domain.JG;
import com.serialPort.web.domain.Jybgmxzd;
import com.serialPort.web.domain.ObxInfo;
import com.serialPort.web.service.PostTbLisJybgmxzd;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.serialPort.common.utils.massRequestHeaders;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PostTbLisJybgmxzdImpl implements PostTbLisJybgmxzd {
    private static final Logger logger = LoggerFactory.getLogger(PostTbLisJybgmxzdImpl.class);

    @Value("${lisapi.jybgmx}")
    String urls;

    @Value("${lisapi.machineNo}")
    String EQNo;

    @Value("${lisapi.machineName}")
    String EQName;

    @Override
    public Object uploadLis(HL7Message hl7Message) {
        // 创建 HttpClient
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String url = urls;
            // 创建 HTTP POST 请求
            HttpPost httpPost = HttpClientUtils.createHttpPost(url);

            //请求头封装类
            Map<String, String> stringStringMap = massRequestHeaders.buildHeaders();
            // 设置请求头
            for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            //请求参数
            Jybgmxzd jybgmxzd = new Jybgmxzd();
            //项目编号
            jybgmxzd.setCJYXH(hl7Message.getSampleInfo().getCodeNum());
            String systemTime = hl7Message.getSystemInfo().getSystemTime();
            String jysj = hl7Message.getSampleInfo().getProvTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date parse = simpleDateFormat.parse(jysj);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            jybgmxzd.setCJYSJ(formatter.format(parse));
            jybgmxzd.setCJGID("1663468925972856833");
            jybgmxzd.setEQNo(EQNo);
            jybgmxzd.setEQName(EQName);
            List<JG> jgList = new ArrayList<>();
            for (ObxInfo obxInfo : hl7Message.getObxInfoList()) {
                JG jg = new JG();
                jg.setCTDH(obxInfo.getProcName());
                jg.setCJG(obxInfo.getResult());
                jgList.add(jg);
            }
            jybgmxzd.setJGList(jgList);
            // 记录请求参数
            logger.info("上传lis请求参数: " + jybgmxzd);
            //设置请求体
            StringEntity entitys = new StringEntity(jybgmxzd.toString(), StandardCharsets.UTF_8);
            httpPost.setEntity(entitys);
            // 发送请求并接收响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            // 处理响应
            if (entity != null) {
                String responseBody = EntityUtils.toString(entity);
                // 记录响应
                logger.info("上传lis返回响应: {}", responseBody);
                // 解析 JSON 字符串为 JSONObject

                JSONObject jsonObject = new JSONObject(responseBody);

                return jsonObject.get("code");

            } else {
                logger.error("返回响应数据为空!" + entity);
            }
        } catch (Exception e) {
            logger.error("上传list出现错误，原因为：" + e.getMessage());
            // 记录错误
        }
        return null;
    }
}
